import dataPreferences from '@ohos.data.preferences'

/**
 * 本地存储工具类
 */
export class StorageUtil {
  private static preferences: dataPreferences.Preferences

  /**
   * 初始化存储
   */
  static async initPreferences(context: Context) {
    try {
      this.preferences = await dataPreferences.getPreferences(context, 'campus_delivery')
      console.info('Storage initialized successfully')
    } catch (error) {
      console.error('Failed to initialize storage:', error)
    }
  }

  /**
   * 保存数据
   */
  static async setData(key: string, value: any): Promise<boolean> {
    try {
      if (typeof value === 'object') {
        value = JSON.stringify(value)
      }
      await this.preferences.put(key, value)
      await this.preferences.flush()
      return true
    } catch (error) {
      console.error('Failed to save data:', error)
      return false
    }
  }

  /**
   * 获取数据
   */
  static async getData(key: string, defaultValue?: any): Promise<any> {
    try {
      const value = await this.preferences.get(key, defaultValue)
      if (typeof value === 'string' && this.isJsonString(value)) {
        return JSON.parse(value)
      }
      return value
    } catch (error) {
      console.error('Failed to get data:', error)
      return defaultValue
    }
  }

  /**
   * 删除数据
   */
  static async removeData(key: string): Promise<boolean> {
    try {
      await this.preferences.delete(key)
      await this.preferences.flush()
      return true
    } catch (error) {
      console.error('Failed to remove data:', error)
      return false
    }
  }

  /**
   * 清空所有数据
   */
  static async clearAll(): Promise<boolean> {
    try {
      await this.preferences.clear()
      await this.preferences.flush()
      return true
    } catch (error) {
      console.error('Failed to clear data:', error)
      return false
    }
  }

  /**
   * 检查是否为JSON字符串
   */
  private static isJsonString(str: string): boolean {
    try {
      JSON.parse(str)
      return true
    } catch {
      return false
    }
  }

  /**
   * 保存用户信息
   */
  static async saveUserInfo(userInfo: any): Promise<boolean> {
    return await this.setData('user_info', userInfo)
  }

  /**
   * 获取用户信息
   */
  static async getUserInfo(): Promise<any> {
    return await this.getData('user_info', {})
  }

  /**
   * 保存token
   */
  static async saveToken(token: string): Promise<boolean> {
    return await this.setData('access_token', token)
  }

  /**
   * 获取token
   */
  static async getToken(): Promise<string> {
    return await this.getData('access_token', '')
  }

  /**
   * 保存购物车数据
   */
  static async saveCart(cartItems: any[]): Promise<boolean> {
    return await this.setData('shopping_cart', cartItems)
  }

  /**
   * 获取购物车数据
   */
  static async getCart(): Promise<any[]> {
    return await this.getData('shopping_cart', [])
  }

  /**
   * 保存地址信息
   */
  static async saveAddresses(addresses: any[]): Promise<boolean> {
    return await this.setData('delivery_address', addresses)
  }

  /**
   * 获取地址信息
   */
  static async getAddresses(): Promise<any[]> {
    return await this.getData('delivery_address', [])
  }

  /**
   * 删除token（退出登录）
   */
  static async removeToken(): Promise<boolean> {
    return await this.removeData('access_token')
  }

  /**
   * 检查是否登录
   */
  static async isLoggedIn(): Promise<boolean> {
    const token = await this.getToken()
    return !!token
  }
}